package com.llb666.shop.payment.infrastructure.utils;

import com.llb666.common.core.utils.sign.MD5Utils;
import com.llb666.shop.payment.infrastructure.config.WXPayConfig;

import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class Sign {
    /**
     * 微信支付签名算法sign.
     *
     * @param characterEncoding 编码
     * @param parameters        参数
     * @return 签名
     */
    public static String createSign(String characterEncoding,
                                    SortedMap<Object, Object> parameters, String key) {

        StringBuilder sb = new StringBuilder();

        // 所有参与传参的参数按照accSii排序（升序）
        Set<Map.Entry<Object, Object>> entries = parameters.entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);

        return MD5Utils.MD5Encode(sb.toString(), characterEncoding)
                .toUpperCase();
    }

    public static String createSign(WXPayConfig wxPayConfig, String body, String nonce_str, String outTradeNo, String totalFee) {
        SortedMap<Object, Object> map = new TreeMap<>();
        map.put("appid", wxPayConfig.getAppId());
        map.put("mch_id", wxPayConfig.getMerchantId());
        map.put("body", body);
        map.put("nonce_str", nonce_str);
        map.put("out_trade_no", outTradeNo);
        map.put("total_fee", totalFee);
        map.put("spbill_create_ip", wxPayConfig.getSpbillCreateIp());
        map.put("notify_url", wxPayConfig.getNotifyUrl());
        map.put("trade_type", wxPayConfig.getTradeType());
        return createSign("utf-8", map, wxPayConfig.getSecretKey());
    }
}
